import { describe } from '$lib';
import { Clock } from '$lib/clock';
import { Heart } from '$lib/content/heart';
import { Types, defineComponent } from '$lib/ecs';
import { logVisible } from '$lib/render3';
import { registerAI } from '$lib/simulate';
import { decode } from '$lib/util';

export const TalkNPC = defineComponent('TalkNPC', {
  id: [Types.ui8, 32],
  line: Types.ui32,
});

const talkNPCs = new Map();

export const registerTalkNPC = (id: string, lines: string[]) => {
  talkNPCs.set(id, lines);
};

registerAI({
  target: TalkNPC,
  action: (world: IWorld, e: Entity) => {
    console.log('NPC Talks');
    const delay = Heart.heartbeat[e];
    const lines = talkNPCs.get(decode(TalkNPC.id[e]));
    const n = TalkNPC.line[e];
    if (n < lines.length) {
      ++TalkNPC.line[e];
      const what = lines ? '"'+lines[n]+'"' : 'something';
      logVisible(e, `${describe(world, e)} says ${what}`, 'npc-message');
    }
    Clock.time[e] += delay;
  },
});
